#import "TopicDetailController.h"
#import <QuartzCore/QuartzCore.h>
#import "UserManager.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"
#import "TopicReplyCell.h"
#import "TopicReplyModel.h"
#import "RegexKitLite.h"
#import "FileManager.h"
#import "CoreDataManager.h"
#import "TopicDetailModel.h"
#import "NetWorkManager.h"

//#define TOPIC_IMAGE_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/TopicDetail"]

@implementation TopicDetailController

@synthesize topic,topicManager;
@synthesize userStateLogin,userStateLogout,currentUserState;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.userStateLogin =[[TDCUserStateLogin alloc]init:self];
        self.userStateLogout =[[TDCUserStateLogout alloc]init:self];
    }
    return self;
}

-(void)dealloc
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(topicTitle);
    PP_RELEASE(topicTime);
    PP_RELEASE(replyTable);
    PP_RELEASE(mainView);
    PP_RELEASE(insideContent);
    PP_RELEASE(topicMainView);
    PP_RELEASE(topicDetailBg);
    PP_RELEASE(replyField);
    PP_RELEASE(topic);
    PP_RELEASE(topicManager);
    PP_RELEASE(topicActionBarContainer);
    PP_RELEASE(topicActionBar);
    PP_RELEASE(shareViewController);
    PP_RELEASE(topic);
    PP_RELEASE(topicManager);
    PP_RELEASE(userStateLogin);
    PP_RELEASE(userStateLogout);
    PP_RELEASE(currentUserState);
    PP_RELEASE(topicDetailModel);
    PP_RELEASE(viewContent);
    PP_RELEASE(loadingImgView);
    PP_RELEASE(realPicsIndex);
    PP_RELEASE(browserPhotos);
    [super  dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.wantsFullScreenLayout = NO;
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    self.viewDeckController.delegate = self;
    baseTitle.text = @"编辑推荐";
    [topic.replies removeAllObjects];
    
    UIButton* backBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0, 0.0, 44, 44)] autorelease];
    //点击前后的图片
    [backBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_1.png"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_2.png"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* backBarBtn= [[[UIBarButtonItem alloc] initWithCustomView:backBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:backBarBtn];
    
    NSArray *acitonNibList = [[NSBundle mainBundle] loadNibNamed:@"TopicActionBar" owner:self options:nil];
    topicActionBar = [[acitonNibList objectAtIndex:0] retain];
    [topicActionBarContainer addSubview:topicActionBar];
    [topicActionBar start:self];
    
    mainView.delegate= self;
    
    needVerify = NO;
    [self start];
    [self baseInitComment:self btnName:@"评论"];
}

- (void)findMisbehavingScrollViews
{
    UIView *view = [[UIApplication sharedApplication] keyWindow];
    [self findMisbehavingScrollViewsIn:view];
}

- (void)findMisbehavingScrollViewsIn:(UIView *)view
{
    if ([view isKindOfClass:[UIScrollView class]])
    {
        NSLog(@"Found UIScrollView: %@", view);
        if ([(UIScrollView *)view scrollsToTop])
        {
            NSLog(@"scrollsToTop = YES!");
            [(UIScrollView *)view setScrollsToTop:NO];
        }
    }
    for (UIView *subview in [view subviews])
    {
        [self findMisbehavingScrollViewsIn:subview];
    }
}

-(void)viewDidUnload
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(topicTitle);
    PP_RELEASE(topicTime);
    PP_RELEASE(replyTable);
    PP_RELEASE(mainView);
    PP_RELEASE(insideContent);
    PP_RELEASE(topicMainView);
    PP_RELEASE(topicDetailBg);
    PP_RELEASE(replyField);
    PP_RELEASE(topic);
    PP_RELEASE(topicManager);
    PP_RELEASE(topicActionBarContainer);
    PP_RELEASE(topicActionBar);
    PP_RELEASE(shareViewController);
    PP_RELEASE(topic);
    PP_RELEASE(topicManager);
    PP_RELEASE(userStateLogin);
    PP_RELEASE(userStateLogout);
    PP_RELEASE(currentUserState);
    PP_RELEASE(topicDetailModel);
    PP_RELEASE(viewContent);
    PP_RELEASE(loadingImgView);
    PP_RELEASE(realPicsIndex);
    PP_RELEASE(browserPhotos);
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [self autologin];
}

#pragma mark -
#pragma mark -------业务方法-------

- (void)autologin {
    UserManager *userManager = [UserManager sharedInstance];
    Log(@"isLogin: %@",userManager.isLogin?@"YES":@"NO");
    if (userManager.isLogin ) {
        [self setUserState:self.userStateLogin];
    }else{
        [self setUserState:self.userStateLogout];
    }
}

- (void)setUserState:(TDCUserStateBase *)newState {
    dispatch_async(dispatch_get_main_queue(), ^{
        currentUserState = newState;
    });
}

//获取coredata，如果没有，http请求topicContent,并存入topic,然后产生coredata;
-(void)start {
    hudLoading.hidden = NO;
    hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hudLoading.opacity = PP_mbprogressHudOpacity;
    hudLoading.labelText = @"正在加载...";

    topicTitle.text = topic.topicTitle;
    topicTime.text = topic.topicTime;
    
    topicDetailModel = [[TopicDetailModel alloc]init];
    topicDetailModel.topicId = topic.topicId;
    
    BOOL topicExistInCoredata = [[CoreDataManager sharedInstance] coredataTopicDetailSelect:topicDetailModel];
    //coredata里有
    if (topicExistInCoredata) {
        needVerify = YES;
        //先展示
        dispatch_async(dispatch_get_main_queue(), ^{
            //下一步展示
            [self show];
        });
    }else{
        needVerify = NO;
        if ([[NetWorkManager sharedInstance]hasNetwork]) {
            //请求新的去
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                TopicModel *tTopic = [topicManager httpTopicDetail:topic.topicId];
                if( tTopic == nil){
                    sleep(0.2);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Wrong.png"]] autorelease];
                        hudLoading.labelText = @"网络错误，请稍后再试";
                        hudLoading.delegate = self;
                        hudLoading.mode = MBProgressHUDModeCustomView;
                        [hudLoading hide:YES afterDelay:1];
                    });
                    return;
                }
                
                topic.topicContent = tTopic.topicContent;
                for (int i = 0; i < topic.topicContent.count; i++) {
                    [topicDetailModel.contentDict setValue:[topic.topicContent objectAtIndex:i] forKey:[NSString stringWithFormat:@"%d",i]];
                }
                [[CoreDataManager sharedInstance] coredataInsert:topicDetailModel];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //下一步展示
                    [self show];
                });
            });
        }else{
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                sleep(0.2);
                dispatch_async(dispatch_get_main_queue(), ^{
                    hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Wrong.png"]] autorelease];
                    hudLoading.labelText = @"网络错误，请稍后再试";
                    hudLoading.delegate = self;
                    hudLoading.mode = MBProgressHUDModeCustomView;
                    [hudLoading hide:YES afterDelay:1];
                });
            });
        }
    }
}

- (void)show {
    viewContent = [[NSMutableArray alloc]init];     //所有的视图
    loadingImgView = [[NSMutableArray alloc]init];     //本地loading图
    realPicsIndex = [[NSMutableArray alloc]init];   //真实图片索引
    textTarget = -1;
    textCount = 0;
    
    Log(@"item.count : %d",topicDetailModel.contentDict.count);
    int tTextCount = 0;
    for (int i = 0; i < topicDetailModel.contentDict.count; i++) {
        NSString *one = [topicDetailModel.contentDict objectForKey:[NSString stringWithFormat:@"%d",i]];
        if([one hasPrefix:@"http"]){
            //图片
            CGRect imgRect=CGRectMake(6, 0, 308, 100);
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:imgRect];
            UIImage *image = [UIImage imageNamed:@"loading_success.png"];
            imgView.contentMode = UIViewContentModeScaleAspectFit;
            imgView.clipsToBounds = YES;
            if( image != nil ){
                imgView.image = image;
            }
            [loadingImgView addObject:imgView];
            [realPicsIndex addObject:[NSString stringWithFormat:@"%d",i]];
            [viewContent addObject:imgView];
            [insideContent addSubview:imgView];
        }else{
            //文字
            UIWebView *textLabel = [[[UIWebView alloc] initWithFrame:CGRectMake(15, 15, 290, 1)] autorelease];
            textLabel.userInteractionEnabled = NO;
            textLabel.delegate = self;
            textLabel.backgroundColor = [UIColor clearColor];  //但是这个属性必须用代码设置，光 xib 设置不行
            textLabel.opaque = NO;
            textLabel.dataDetectorTypes = UIDataDetectorTypeNone;
            NSString *webviewText = @"<style>body{margin:0;background-color:transparent;font:16px/25px Custom-Font-Name}</style>";
            NSString *htmlString = [one stringByReplacingOccurrencesOfString:@"\r\n"    withString:@"<br />"];
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"\n"         withString:@"<br />"];
            htmlString = [htmlString stringByReplacingOccurrencesOfString:@"\r"         withString:@"<br />"];
            tTextCount++;
            [textLabel loadHTMLString:[webviewText stringByAppendingFormat:@"%@", htmlString] baseURL:nil];
            [viewContent addObject:textLabel];
            [insideContent addSubview:textLabel];
        }
    }
    @synchronized(self){
        textTarget = tTextCount + 1;
        [self webViewDidFinishLoad:nil];
        [hudLoading setHidden:YES];
    }
}

#pragma mark -
#pragma mark ----MBProgressHUD delegate----
- (void)hudWasHidden:(MBProgressHUD *)hud
{
    [self back:nil];
}

#pragma mark -
#pragma mark ----UIWebview delegete----

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    BOOL done = NO;
    @synchronized(self){
        textCount++;
        if(textTarget>0 && textCount==textTarget){
            done = YES;
        }
//        Log(@"test textTarget:%d textCount:%d",textTarget,textCount);
    }
    if( webView != nil ){
        float labelHeight = [[webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollHeight"] floatValue];
        CGRect textFrame = webView.frame;
        textFrame.size.height = labelHeight;
        webView.frame = textFrame;
    }
    if( !done ){
        return;
    }
    [self rangeView:viewContent];
    
    int countNum = realPicsIndex.count;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if( countNum == 0 ){
            [self verify];
            return;
        }
        Log(@"pic.count : %d, cache.count : %d",realPicsIndex.count, topicDetailModel.pathDict.count);
        
        browserPhotos = [[NSMutableArray alloc] init];
        MWPhoto *mwphoto;
        
     
        //有图需要换图
        for (int i = 0; i < countNum; i++) {
            BOOL imageExsit = NO;
            NSString *imageName = [topicDetailModel.pathDict objectForKey:[realPicsIndex objectAtIndex:i]];
            Log(@"imageName-------:%@",imageName);
            if (imageName != nil) {
                imageExsit = [[FileManager sharedInstance]imageExsit:imageName andFolder:TOPIC_IMAGE_FOLDER];
                if( !imageExsit ){
                    [topicDetailModel.pathDict removeObjectForKey:[realPicsIndex objectAtIndex:i]];
                    Log(@"index %d, wrong path! cache not exist : %@",i,imageName);
                    [[CoreDataManager sharedInstance]coredataTopicDetailUpdate:topicDetailModel];
                }
            }
            
            UIImage *showImage = nil;
            if (imageExsit) {
                Log(@"index %d, loading cache : %@",i,imageName);
                showImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",TOPIC_IMAGE_FOLDER,imageName]];
                mwphoto = [MWPhoto photoWithImage:showImage];
                [browserPhotos addObject:mwphoto];
                if( showImage == nil ) {
                    imageExsit = NO;
                    [[FileManager sharedInstance] deleteFile:imageName];
                    [topicDetailModel.pathDict removeObjectForKey:[realPicsIndex objectAtIndex:i]];
                    Log(@"index %d, load cache failed : %@",i,imageName);
                    [[CoreDataManager sharedInstance]coredataTopicDetailUpdate:topicDetailModel];
                }
            }
            if(!imageExsit){
                //下载图片到本地并获取图片本地地址
                NSString *remoteUrl = [[[topicDetailModel.contentDict objectForKey:[realPicsIndex objectAtIndex:i]] copy] autorelease];
                Log(@"index %d, downloading : %@",i,remoteUrl);
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:remoteUrl]];
                if (imageData == nil) {  //data如果为nil，直接跳过
                    continue;
                }
                showImage = [UIImage imageWithData:imageData];
                imageName = [[FileManager sharedInstance]saveTopicDetailImg:imageData withUrl:remoteUrl];
                mwphoto = [MWPhoto photoWithImage:showImage];
                [browserPhotos addObject:mwphoto];
                if( imageName ){
                    [topicDetailModel.pathDict setValue:imageName forKey:[realPicsIndex objectAtIndex:i]];
                    Log(@"index %d, saving cache : %@",i,imageName);
                    [[CoreDataManager sharedInstance] coredataTopicDetailUpdate:topicDetailModel];
                }
            }
            UIImageView *imgLocal = [loadingImgView objectAtIndex:i];
            dispatch_async(dispatch_get_main_queue(), ^{
                float imageHeight = 0;
                if (showImage.size.width < 308 ) {
                    imageHeight = showImage.size.height;
                    imgLocal.frame = CGRectMake(imgLocal.frame.origin.x,imgLocal.frame.origin.y,showImage.size.width,imageHeight);
                }else{
                    imageHeight = 308*showImage.size.height/showImage.size.width;
                    imgLocal.frame = CGRectMake(imgLocal.frame.origin.x,imgLocal.frame.origin.y,308,imageHeight);
                }
                imgLocal.userInteractionEnabled = YES;
                UITapGestureRecognizer *tapImage = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanPhotos)];
                tapImage.numberOfTouchesRequired = 1;
                tapImage.numberOfTapsRequired = 1;
                [imgLocal addGestureRecognizer:tapImage];
                [tapImage release];
//                //创建图片浏览器按钮
//                UIButton *imgButton = [[[UIButton alloc]initWithFrame:imgLocal.frame]autorelease];
//                [imgButton addTarget:self action:@selector(scanPhotos) forControlEvents:UIControlEventTouchUpInside];
//                [mainView addSubview:imgButton];
                
                [self rangeView:viewContent];
                imgLocal.image = showImage;
            });
        }
        
        //等到图片加载完毕的时候再去做请求
        [self verify];
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSMutableArray *tReplies = [topicManager httpGetReplySync:topic.topicId];
        [topic.replies removeAllObjects];
        for( TopicReplyModel *one in tReplies){
            [topic.replies addObject:one];
        }
        [tReplies release];
        dispatch_async(dispatch_get_main_queue(), ^{
            [replyTable reloadData];
            replyCountView.text = [NSString stringWithFormat:@"%d条评论",topic.replies.count];

            CGRect replyTableFrame = replyTable.frame;
            replyTableFrame.size.height = replyTable.contentSize.height;
            replyTable.frame = replyTableFrame;
            
            CGRect replyFrame = replyView.frame;
            replyFrame.origin.y = topicMainView.frame.origin.y + topicMainView.frame.size.height;
            replyFrame.size.height = replyTableFrame.origin.y + replyTableFrame.size.height + 10;
            replyView.frame = replyFrame;
            replyViewBg.image = [[UIImage imageNamed:@"joke_page_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
            
            CGSize mainContentFrame = mainView.contentSize;
            mainContentFrame.height = replyFrame.origin.y + replyFrame.size.height + 80;
            mainView.contentSize = mainContentFrame;
            
            [self findMisbehavingScrollViews];
            mainView.scrollsToTop = YES;
        });
    });
}



- (void)verify{
    if( needVerify ){
        needVerify = NO;
        if ([[NetWorkManager sharedInstance]hasNetwork]) {
            //请求并做对比
            TopicModel *tempTopic = [topicManager httpTopicDetail:topic.topicId];
            if( tempTopic == nil){
                return;
            }
            
            NSMutableDictionary *tempDict = [[[NSMutableDictionary alloc]init]autorelease];
            for (int i = 0; i < tempTopic.topicContent.count; i++) {
                [tempDict setValue:[tempTopic.topicContent objectAtIndex:i] forKey:[NSString stringWithFormat:@"%d",i]];
            }
            
            if ([tempDict isEqualToDictionary:topicDetailModel.contentDict]) {
                return;
            }else{
                topicDetailModel.contentDict = tempDict;
                [[CoreDataManager sharedInstance] coredataTopicDetailUpdate:topicDetailModel];
                dispatch_async(dispatch_get_main_queue(), ^{
                    for(UIView *view in [insideContent subviews])
                    {
                        [view removeFromSuperview];
                    }
                    [self show];
                });
            }
        }
    }
}

- (void)scanPhotos{
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    nc.modalTransitionStyle = UIModalPresentationFullScreen ;
    [self presentModalViewController:nc animated:YES];
    [nc release];
}

-(void)rangeView:(NSMutableArray *)array {
    insideContent.frame = CGRectMake(insideContent.frame.origin.x, insideContent.frame.origin.y, insideContent.frame.size.width, insideContent.frame.size.height);
    
//    Log(@"count: %d",array.count);
    float yHeight = 0;
    for (int i = 0; i<array.count; i++) {
        id obj = [array objectAtIndex:i];
        if([obj isKindOfClass:[UIWebView class]]){
            UIWebView *web = (UIWebView *)obj;
            web.frame = CGRectMake(web.frame.origin.x,yHeight,web.frame.size.width,web.frame.size.height);
            yHeight += web.frame.size.height;
        } else if( [obj isKindOfClass:[UIImageView class]] ){
            UIImageView *img = (UIImageView *)obj;
            img.frame = CGRectMake(img.frame.origin.x,yHeight,img.frame.size.width,img.frame.size.height);
            yHeight += img.frame.size.height;
        }
        //        [insideContent addSubview:obj];
    }
    
    CGRect textFrame = insideContent.frame;
    insideContent.frame = CGRectMake(textFrame.origin.x,textFrame.origin.y,textFrame.size.width,yHeight);
    topicDetailBg.frame = CGRectMake(topicDetailBg.frame.origin.x, topicDetailBg.frame.origin.y,  topicDetailBg.frame.size.width, yHeight+130);
    topicMainView.frame = CGRectMake(topicMainView.frame.origin.x,topicMainView.frame.origin.y,topicMainView.frame.size.width,yHeight+150);

//    CGRect topicBottomFrame = topicBottomImg.frame;
//    topicBottomImg.frame = CGRectMake(topicBottomFrame.origin.x, topicMainView.frame.size.height, topicBottomFrame.size.width, topicBottomFrame.size.height);
    
    //回复内容的 y 坐标在topicMainView的下面
    
    CGRect replyTableFrame = replyTable.frame;
    replyTableFrame.size.height = replyTable.contentSize.height;
    replyTable.frame = replyTableFrame;
    
    CGRect replyFrame = replyView.frame;
    replyFrame.origin.y = topicMainView.frame.origin.y + topicMainView.frame.size.height;
    replyFrame.size.height = replyTableFrame.origin.y + replyTableFrame.size.height + 10;
    replyView.frame = replyFrame;
    replyViewBg.image = [[UIImage imageNamed:@"joke_page_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    
    CGSize mainContentFrame = mainView.contentSize;
    mainContentFrame.height = replyFrame.origin.y + replyFrame.size.height + 80;
    mainView.contentSize = mainContentFrame;
    
    UIImage *inpugBackGround = [[UIImage imageNamed:@"post_input.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    topicDetailBg.image = inpugBackGround;
}

- (void)startComment {
    [self baseShowComment];
}

- (void)startFavorite {
    ;
}

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    static BOOL hidden = NO;
    static int gap = 40;
    static int lastContentOffset = 40;
    
    [self baseHideComment];
    ScrollDirection scrollDirection;
    if(sender.contentOffset.y == 0 ){
        if( hidden ){
            Log(@"top");
            hidden = NO;
            [self showBar];
        }
    } else if(sender.contentSize.height - 80 - gap - sender.contentOffset.y <= sender.frame.size.height){
        if( hidden ){
            Log(@"bottom");
            hidden = NO;
            [self showBar];
        }
    }else if (lastContentOffset - sender.contentOffset.y > gap){
        scrollDirection = ScrollDirectionUp;
        if( hidden ){
            Log(@"up");
            hidden = NO;
            [self showBar];
        }
    }else if (sender.contentOffset.y - lastContentOffset > gap){
        scrollDirection = ScrollDirectionDown;
        if( !hidden ){
            Log(@"down");
            hidden = YES;
            [self hideBar];
        }
    }
    if( fabs(lastContentOffset-sender.contentOffset.y)>=gap ){
        lastContentOffset = sender.contentOffset.y;
    }
}

- (void)hideBar {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        CGRect barFrame = topicActionBarContainer.frame;
        barFrame.origin.y = mainView.frame.origin.y + mainView.frame.size.height;
        topicActionBarContainer.frame = barFrame;
        [UIView commitAnimations];
    });
}

- (void)showBar {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        CGRect barFrame = topicActionBarContainer.frame;
        barFrame.origin.y = mainView.frame.origin.y + mainView.frame.size.height - barFrame.size.height;
        topicActionBarContainer.frame = barFrame;
        [UIView commitAnimations];
    });
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma 表格数据源

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// 有几组数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(topic==nil || topic.replies==nil){
        return 0;
    }else{
        return [topic.replies count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *topicCellIdentifier = @"TopicReplyCell";
    TopicReplyCell *cell = (TopicReplyCell *)[replyTable dequeueReusableCellWithIdentifier:topicCellIdentifier];
    if (cell==nil)
    {
        NSArray *nibList = [[NSBundle mainBundle] loadNibNamed:topicCellIdentifier owner:self options:nil];
        for(id obj in nibList)
        {
            if([obj isKindOfClass:[TopicReplyCell class]])
            {
                cell=(TopicReplyCell *)obj;
            }
        }
    }
    
    TopicReplyModel *tReply = [topic.replies objectAtIndex:indexPath.row];
    [cell setReplyText:tReply.replyText withName:tReply.replyName withFloor:[NSString stringWithFormat:@"%dF",indexPath.row+1]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone; //cell不可点击
    return cell;
}

#pragma mark -
#pragma mark -------JokeActionBarDelegate 协议方法-------

- (void)TABshare {
    [shareViewController release];
    shareViewController = [[ShareViewController alloc] initWithNibName:@"ShareViewController" bundle:nil];
    shareViewController.owner = self;
    [self presentPopupViewController:shareViewController animationType:MJPopupViewAnimationFade];
}

- (void)TABcomment {
    [currentUserState TDCUScomment];
}

- (void)TABfavorite {
    [currentUserState TDCUSfavorite];
}

- (void)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)BVCcommentDone:(HPGrowingTextView *)commentField {
    Log(@"commentField.text:%@ , count:%d",commentField.text,[commentField.text length]);
    if ([commentField.text length] == 0) {
        [self baseShowInfoHud:NSLocalizedString(@"随便说点什么吧", @"") andIsTop:YES];
        return;
    }
    
    NSString *tText = [commentField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];//去掉首尾空格
    if ([tText length] == 0) {
        [self baseShowInfoHud:NSLocalizedString(@"元方,空格你怎么看?", @"") andIsTop:YES];
        return;
    }
    
    [commentField resignFirstResponder];
    HAS_NO_NETWORK(self);
//    [self baseShowInfoHud:NSLocalizedString(@"正在发表", @"") andIsTop:NO];

    hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hudLoading.labelText = @"正在发表...";
    hudLoading.opacity = PP_mbprogressHudOpacity;

    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        Log(@"replying");
//        ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:TOPIC_DETAIL_SEND_REPLY_URL]];
//        request.userAgentString = @"lxh_app2_100";
//        [request setAllowCompressedResponse:YES];
//        [request addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"webpy_session_id=%@",[UserManager sharedInstance].sessionId] ];
//        [request setPostValue:@"postComment" forKey:@"action"];
//        [request setPostValue:[NSString stringWithFormat:@"%@",topic.topicId] forKey:@"joke_id"];
//        [request setPostValue:[NSString stringWithFormat:@"%@",topic.topicId] forKey:@"gather_id"];
//        [request setPostValue:tText forKey:@"content"];
//        [request setDelegate:self];
//        [request startSynchronous];
        
        ASIFormDataRequest_POST(TOPIC_DETAIL_SEND_REPLY_URL);        
        [request setPostValue:@"postComment" forKey:@"action"];
        [request setPostValue:[NSString stringWithFormat:@"%@",topic.topicId] forKey:@"joke_id"];
        [request setPostValue:[NSString stringWithFormat:@"%@",topic.topicId] forKey:@"gather_id"];
        [request setPostValue:tText forKey:@"content"];
        [request setDelegate:self];
        [request startSynchronous]; 
        
        NSError *error = [request error];
        NSString *res;
        if(!error){
            NSString *tResponseStr = [request responseString];
            Log(@"res: %@",tResponseStr);
            SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
            id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
            [tJsonParser release], tJsonParser = nil;
            if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
                BOOL is_success = [[(NSDictionary *)tJsonObjects objectForKey:@"success"] boolValue];
                if (is_success) {
                    NSString *username = [(NSDictionary *)tJsonObjects objectForKey:@"author_user_name"];
                    Log(@"done. username: %@",username);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        TopicReplyModel *one = [[[TopicReplyModel alloc] init] autorelease];
                        [one setReplyName:username];
                        [one setReplyText:commentField.text];
                        [topic.replies addObject:one];
                        [commentField resignFirstResponder];
                        [replyTable reloadData];
                        replyCountView.text = [NSString stringWithFormat:@"%d条评论",topic.replies.count];
                        
                        
                        CGRect replyTableFrame = replyTable.frame;
                        replyTableFrame.size.height = replyTable.contentSize.height;
                        replyTable.frame = replyTableFrame;
                        
                        CGRect replyFrame = replyView.frame;
                        replyFrame.origin.y = topicMainView.frame.origin.y + topicMainView.frame.size.height;
                        replyFrame.size.height = replyTableFrame.origin.y + replyTableFrame.size.height + 10;
                        replyView.frame = replyFrame;
                        replyViewBg.image = [[UIImage imageNamed:@"joke_page_bg.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
                        
                        CGSize mainContentFrame = mainView.contentSize;
                        mainContentFrame.height = replyFrame.origin.y + replyFrame.size.height + 80;
                        mainView.contentSize = mainContentFrame;
//                        [self baseShowInfoHud:NSLocalizedString(@"发表评论成功", @"") andIsTop:NO];
                        
                        hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
                        hudLoading.labelText = @"发表评论成功";
                        hudLoading.mode = MBProgressHUDModeCustomView;
                        [hudLoading hide:YES afterDelay:0.5];
                                                
                        commentField.text = @"";
                    });
                    return;
                }else {
                    res = [(NSDictionary *)tJsonObjects objectForKey:@"error"];
                    Log ( @"failed: %@",res);
                }
            }else{
                res = @"服务器出错，请稍后再试";
                Log ( @"failed: %@",res);
            }
        }else{
            Log ( @"failed: %@",[error description]);
            res = @"网络异常,请稍后再试";
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [commentField resignFirstResponder];
//            [self baseShowHUD:res atY:-60.0f];
//            [self baseShowInfoHud:NSLocalizedString(res, @"") andIsTop:NO];
            hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Wrong.png"]] autorelease];
            hudLoading.labelText = res;
            hudLoading.mode = MBProgressHUDModeCustomView;
            [hudLoading hide:YES afterDelay:0.5];
            commentField.text = @"";
        });
    });
}

- (void)BVCcommentHide:(UIView *)commentView {
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch = [touches anyObject];
    CGPoint pt = [touch locationInView:self.view];
    if(CGRectContainsPoint(self.baseCommentView.frame,pt)){
    }else{
        [self baseHideComment];
    }
}

#pragma mark -
#pragma mark -------ShareViewDelegate 协议方法-------

- (void)SVDcancel {
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}

- (void)SVDweixin {
    [[ShareManager sharedInstance] weixinShare:self];
}

- (void)SVDweixinFriends {
    [[ShareManager sharedInstance] weixinFriends:self];
}

- (void)SVDsinaWeibo {
    [[ShareManager sharedInstance] sinaWeibo:self];
}

- (void)SVDtencentWeibo {
    [[ShareManager sharedInstance] tencentWeibo:self];
}

- (void)SVDdouban {
    [[ShareManager sharedInstance] douban:self];
}

- (void)SVDqzone {
    [[ShareManager sharedInstance] qzone:self];
}

- (void)SVDrenren {
    [[ShareManager sharedInstance] renren:self];
}

- (void)SVDsmsMessage {
    [[ShareManager sharedInstance] smsMessage:self];
}

- (void)SVDcopy {
    [[ShareManager sharedInstance] copy:TOPIC_SHAREURL(topic.topicId)];
    [self baseShowInfoHud:@"已复制链接至剪贴板" andIsTop:NO];
}

#pragma mark -
#pragma mark -------ShareDataDelegate协议方法-------

- (ShareModel*)SMDdata {
    ShareModel *data = [[ShareModel alloc] init];
    data.title = topic.topicTitle;
    data.text = topic.topicText;
    data.url = TOPIC_SHAREURL(topic.topicId);
    data.image = nil;
    NSData *imageData = UIImageJPEGRepresentation(topic.topicImg, 0.8);
    if (imageData != nil && [imageData length]/1024 < 32) {
        data.thumbImage = [[UIImage alloc] initWithData:imageData];
    }else{
        data.thumbImage = [UIImage imageNamed:@"icon_about.png"];
    }
    
    NSString *content = [NSString stringWithFormat:@"%@ ...详情请点击 %@",topic.topicTitle,TOPIC_SHAREURL(topic.topicId)];
    data.weiboText = content;
    return data;
}

- (void)viewDeckController:(IIViewDeckController*)viewDeckController didChangeOffset:(CGFloat)offset orientation:(IIViewDeckOffsetOrientation)orientation panning:(BOOL)panning{
    [self baseHideComment];
}

#pragma mark -------MWPhotoBrowserDelegate方法------

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return browserPhotos.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < browserPhotos.count){
        return [browserPhotos objectAtIndex:index];
    }
    return nil;
}

@end



#pragma mark -------登录状态机 -------

@implementation TDCUserStateBase

-(id)init:(TopicDetailController *)powner {
    self = [super init];
    if (self) {
        owner = powner;
    }
    return self;
}
@end

@implementation TDCUserStateLogin:TDCUserStateBase
-(void)TDCUScomment{
    [owner startComment];
}
-(void)TDCUSfavorite{
    [owner startFavorite];
}
@end

@implementation TDCUserStateLogout:TDCUserStateBase
-(void)TDCUScomment{
    [owner baseShowLoginSheet];
}
-(void)TDCUSfavorite{
    [owner baseShowLoginSheet];
}
@end
